import { ref, onUnmounted } from 'vue';
import { io } from 'socket.io-client';

export function useSocket(url = '_null') {
  const socket = ref(null);
  const isConnected = ref(false);

  // Initialize socket connection
  function connect() {
    socket.value = io(url, {
      autoConnect: true,
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    });

    // Handle connection events
    socket.value.on('connect', () => {
      isConnected.value = true;
      console.log('Socket connected:', socket.value.id);
    });

    socket.value.on('disconnect', () => {
      isConnected.value = false;
      console.log('Socket disconnected');
    });

    socket.value.on('connect_error', (error) => {
      console.error('Socket connection error:', error);
    });
  }

  // Disconnect socket
  function disconnect() {
    if (socket.value) {
      socket.value.disconnect();
      socket.value = null;
      isConnected.value = false;
    }
  }

  // Emit an event to the server
  function emit(event, data) {
    if (socket.value && isConnected.value) {
      console.log('向服务器emit事件')
      socket.value.emit(event, data);
    } else {
      console.warn('Socket is not connected');
    }
  }

  // Listen for an event from the server
  function on(event, callback) {
    if (socket.value) {
      socket.value.on(event, callback);
    }
  }

  // Remove event listener
  function off(event, callback) {
    if (socket.value) {
      socket.value.off(event, callback);
    }
  }

  // Automatically connect when composable is used
  connect();

  // Clean up socket connection when component is unmounted
  onUnmounted(() => {
    disconnect();
  });

  return {
    socket,
    isConnected,
    emit,
    on,
    off,
    connect,
    disconnect,
  };
}
